package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.heima.common.constants.admin.NewsAutoScanConstants;
import com.heima.common.constants.media.WeMediaConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.common.dto.PageResponseResult;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.NewsAuthDto;
import com.heima.model.wemedia.dto.WmNewsDto;
import com.heima.model.wemedia.dto.WmNewsPageReqDto;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmNews;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.MaterialMapper;
import com.heima.wemedia.mapper.NewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Ronaldo
 * @date 2021/8/4
 */
@Service
@Slf4j
@Transactional
@SuppressWarnings("all")
public class NewsServiceImpl extends ServiceImpl<NewsMapper, WmNews> implements NewsService {

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private NewsMapper newsMapper;

    @Override
    public ResponseResult queryNewsListByPage(WmNewsPageReqDto newsPageReqDto) {
        //分页参数检查
        newsPageReqDto.checkParam();

        //判断是否用户登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (Objects.isNull(user)) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        LambdaQueryWrapper<WmNews> newsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //状态
        if (Objects.nonNull(newsPageReqDto.getStatus())) {
            newsLambdaQueryWrapper.eq(WmNews::getStatus, newsPageReqDto.getStatus());
        }
        //频道id
        if (Objects.nonNull(newsPageReqDto.getChannelId())) {
            newsLambdaQueryWrapper.eq(WmNews::getChannelId, newsPageReqDto.getChannelId());
        }
        //关键字模糊查询
        if (StringUtils.isNotBlank(newsPageReqDto.getKeyword())) {
            newsLambdaQueryWrapper.like(WmNews::getTitle, newsPageReqDto.getKeyword());
        }
        //发布时间区间查询
        if (Objects.nonNull(newsPageReqDto.getBeginPubDate()) && Objects.nonNull(newsPageReqDto.getEndPubDate())) {
            newsLambdaQueryWrapper.between(WmNews::getPublishTime, newsPageReqDto.getBeginPubDate(), newsPageReqDto.getEndPubDate());
        }

        //必须条件 : 当前用户
        newsLambdaQueryWrapper.eq(WmNews::getUserId, user.getId());

        //创建时间倒排
        newsLambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //分页查询
        IPage<WmNews> page = new Page<>(newsPageReqDto.getPage(), newsPageReqDto.getSize());
        page = this.page(page, newsLambdaQueryWrapper);

        //设置responseResult host属性
        PageResponseResult pageResponseResult = new PageResponseResult(newsPageReqDto.getPage(), newsPageReqDto.getSize(), (int) page.getTotal());
        pageResponseResult.setHost(webSite);
        pageResponseResult.setData(page.getRecords());

        //清理ThreadLocal
        WmThreadLocalUtils.clear();

        return pageResponseResult;
    }

    @Override
    public ResponseResult submit(WmNewsDto newsDto) {

        //参数判断
        if (StringUtils.isBlank(newsDto.getTitle())) {
            throw new LeadNewsException(AppHttpCodeEnum.LACK_TITLE);
        }
        if (Objects.isNull(newsDto.getChannelId())) {
            throw new LeadNewsException(AppHttpCodeEnum.LACK_CHANNEL);
        }
        if (StringUtils.isBlank(newsDto.getLabels())) {
            throw new LeadNewsException(AppHttpCodeEnum.LACK_LABEL);
        }
        if (StringUtils.isBlank(newsDto.getContent())) {
            throw new LeadNewsException(AppHttpCodeEnum.LACK_CONTENT);
        }
        if (Objects.isNull(newsDto.getType())) {
            throw new LeadNewsException(AppHttpCodeEnum.LACK_COVER_TYPE);
        }

        //判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (Objects.isNull(user)) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //参数类型转换为  WmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(newsDto, wmNews);

        //其他属性设置
        wmNews.setUserId(user.getId());
        wmNews.setEnable(WeMediaConstants.WM_NEWS_ENABLE_UP);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        //封面布局类型设置  如果type为自动(-1)  则设置为null
        if (WeMediaConstants.WM_NEWS_TYPE_AUTO.equals(newsDto.getType())) {
            wmNews.setType(null);
        }

        //封面图片设置
        List<String> imageList = newsDto.getImages();
        //去除域名
        imageList = imageList.stream().map(imageStr -> {
            return imageStr.replace(webSite, "").replace(" ", "");
        }).collect(Collectors.toList());
        //将list转换为 , 号分割的字符串
        String imagePath = StringUtils.join(imageList, ",");
        wmNews.setImages(imagePath);

        //更新或保存文章
        insertOrUpdate(wmNews);

        //抽取内容中的图片
        List<String> contentImageList = extractImage(newsDto.getContent());

        //如果当前为提交审核  则执行保存内容图片与文章的关系
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            if (contentImageList.size() > 0) {
                //保存内容图片与文章的关系
                saveRelationship(contentImageList, wmNews.getId(), WeMediaConstants.WM_CONTENT_REFERENCE);
            }
            //保存封面图片与文章的关系
            saveRelationshipForCover(contentImageList, wmNews, newsDto);
        }

        //只有数据更新成功或创建成功 同时 状态必须是待审核，才允许生产消息到MQ中，生产的具体消息是文章ID
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, String.valueOf(wmNews.getId()));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //保存封面图片与文章的关系
    private void saveRelationshipForCover(List<String> contentImageList, WmNews wmNews, WmNewsDto newsDto) {
        //获取封面图片
        List<String> imageList = newsDto.getImages();

        // 设置自动布局 封面图片
        if (WeMediaConstants.WM_NEWS_TYPE_AUTO.equals(newsDto.getType())) {
            int size = contentImageList.size();
            if (size >= 3) {
                //大于等于三 则设置为多图布局 并选择三张文章中的图片作为封面图片
                wmNews.setType(WeMediaConstants.WM_NEWS_MANY_IMAGE);
                imageList = contentImageList.stream().limit(3).collect(Collectors.toList());
            } else if (size >= 1 && size < 3) {
                //大于等于1小于3  设置为单图布局  并选择一张作为封面图片
                wmNews.setType(WeMediaConstants.WM_NEWS_SINGLE_IMAGE);
                imageList = contentImageList.stream().limit(1).collect(Collectors.toList());
            } else {
                // 文章中没有图片时  则设置为无图布局  无封面图片
                wmNews.setType(WeMediaConstants.WM_NEWS_NONE_IMAGE);
                imageList = Lists.newArrayList();
            }

            // 自动布局 WmNews的images字段无值 不设置则前端不会显示图片
            if (imageList.size() > 0) {
                String imagePathStr = StringUtils.join(imageList, ",");
                wmNews.setImages(imagePathStr);
            }

            updateById(wmNews);
        }

        if (CollectionUtils.isNotEmpty(imageList) && imageList.size() > 0) {
            imageList = imageList.stream().map(x -> x.replace(webSite, "").replace(" ", "")).collect(Collectors.toList());
            saveRelationship(imageList, wmNews.getId(), WeMediaConstants.WM_COVER_REFERENCE);
        }

    }

    //公共方法 : 保存图片资源与文章的关系
    private void saveRelationship(List<String> imageList, Integer newsId, Short type) {

        // 根据素材路径  获取  素材列表
        List<WmMaterial> materialList = materialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));

        if (CollectionUtils.isEmpty(materialList) || materialList.size() == 0) {
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_MATERIAL);
        }

        // 判断那些素材url没有查到数据
        Map<String, Integer> materialMap = materialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        List<Integer> materialIdList = Lists.newArrayList();
        for (String imageUrl : imageList) {
            Integer materialId = materialMap.get(imageUrl);
            if (Objects.isNull(materialId)) {
                throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_MATERIAL);
            }
            materialIdList.add(materialId);
        }
        newsMaterialMapper.insertRelationshipList(materialIdList, newsId, type);
    }

    //抽取图文内容中的图片地址
    private List<String> extractImage(String content) {
        List<String> imagePathList = Lists.newArrayList();

        if (StringUtils.isBlank(content)) {
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        List<Map> mapList = JSON.parseArray(content, Map.class);
        for (Map<String, String> map : mapList) {
            if (map.get("type").equals(WeMediaConstants.WM_NEWS_TYPE_IMAGE)) {
                String imagePath = map.get("value");
                imagePath = imagePath.replace(webSite, "").replace(" ", "");
                imagePathList.add(imagePath);
            }
        }
        return imagePathList;
    }

    //保存或更新文章
    private void insertOrUpdate(WmNews wmNews) {

        Integer id = wmNews.getId();
        if (Objects.isNull(id)) {
            //如果没有id则创建文章
            save(wmNews);
        } else {
            //如果有id  则执行修改操作
            //判断文章是否存在
            WmNews news = getById(id);
            if (Objects.isNull(news)) {
                throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_NEWS);
            }
            //保存之前,先删除文章与素材的关联关系
            newsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
            //执行更新
            updateById(wmNews);
        }

    }

    @Override
    public ResponseResult getNewsById(Integer id) {

        WmUser user = WmThreadLocalUtils.getUser();
        if (Objects.isNull(user)) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        WmNews news = getById(id);
        if (Objects.isNull(news)) {
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_NEWS);
        }
        ResponseResult responseResult = ResponseResult.okResult(news);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult deleteNewsById(Integer id) {

        WmUser user = WmThreadLocalUtils.getUser();
        if (Objects.isNull(user)) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        WmNews news = getById(id);
        if (Objects.isNull(news)) {
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_NEWS);
        }

        //如果文章为已发布 并且 是上架状态 不可删除
        if (news.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && news.getEnable().equals(WeMediaConstants.WM_NEWS_ENABLE_UP)) {
            throw new LeadNewsException(AppHttpCodeEnum.NEWS_IS_ENABLE);
        }

        //删除素材于文章关系
        newsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));

        //执行删除文章
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override
    public ResponseResult downOrUp(WmNewsDto newsDto) {

        WmUser user = WmThreadLocalUtils.getUser();
        if (Objects.isNull(user)) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断文章是否存在
        WmNews news = getById(newsDto.getId());
        if (Objects.isNull(news)) {
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_NEWS);
        }

        //判断文章是否已发布
        if (!news.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            throw new LeadNewsException(AppHttpCodeEnum.NEWS_IS_DISABLE);
        }

        //执行上下架操作
        WmNews wmNews = new WmNews();
        wmNews.setId(newsDto.getId());
        wmNews.setEnable(newsDto.getEnable());
        updateById(wmNews);

        //发送消息  使article微服务与自媒体文章  上下架状态一致
        Map map = Maps.newHashMap();
        //app文章id
        map.put("articleId", news.getArticleId());
        //当前是上架  还是  下架
        map.put("enable", newsDto.getEnable());
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult getNewsListForAdmin(NewsAuthDto newsAuthDto) {

        //设置参数中的page
        Integer page = newsAuthDto.getPage();
        newsAuthDto.setPage((page - 1) * newsAuthDto.getSize());

        //分页查询文章列表
        List<WmNewsVo> newsVoList = newsMapper.selectNewsListByAuthDTO(newsAuthDto);

        // 查询文章个数
        Integer total = newsMapper.selectTotalByAuthDTO(newsAuthDto);

        PageResponseResult pageResponseResult = new PageResponseResult(page, newsAuthDto.getSize(), total);
        pageResponseResult.setData(newsVoList);
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    @Override
    public ResponseResult getNewsForAdminById(Integer id) {

        //查询文章
        WmNewsVo newsVo = newsMapper.selectNewsForAdminById(id);

        if (Objects.isNull(newsVo)) {
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_NEWS);
        }
        if (StringUtils.isBlank(newsVo.getAuthorName())) {
            throw new LeadNewsException(AppHttpCodeEnum.NEWS_AUTHOR_IS_NOT_FOUND);
        }

        ResponseResult responseResult = ResponseResult.okResult(newsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult manualScan(NewsAuthDto newsAuthDto, short status) {

        //查询该文章是否存在
        WmNews news = this.getById(newsAuthDto.getId());
        if (Objects.isNull(news)) {
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_NEWS);
        }

        //判断文章是否为待人工审核
        if (!news.getStatus().equals(WmNews.Status.ADMIN_AUTH.getCode())) {
            throw new LeadNewsException(AppHttpCodeEnum.NEWS_STATUS_IS_NOT_ADMIN_AUTH);
        }

        //更新文章信息
        news.setId(newsAuthDto.getId());
        news.setStatus(status);
        if (StringUtils.isNotBlank(newsAuthDto.getMsg())) {
            news.setReason(newsAuthDto.getMsg());
        }
        updateById(news);

        //判断是否人工审核成功  成功则判断发布时间是否小于当前时间 小于则发送消息 发布文章  大于则修改文章状态为8 等待自动发布
        if (news.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())) {
            if (news.getPublishTime().getTime() < System.currentTimeMillis()) {
                kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, String.valueOf(news.getId()));
            } else {
                news.setStatus(WmNews.Status.SUCCESS.getCode());
                updateById(news);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public List<Integer> findReleaseNewsId() {

        //查询条件：状态为4或8的且发布时间小于系统当前时间，只查询ID列
        List<WmNews> newsList = list(Wrappers.<WmNews>lambdaQuery()
                .in(WmNews::getStatus, WmNews.Status.ADMIN_SUCCESS.getCode(), WmNews.Status.SUCCESS.getCode())
                .lt(WmNews::getPublishTime, new Date())
                .select(WmNews::getId)
        );

        List<Integer> newsIdList = newsList.stream().map(news -> {
            return news.getId();
        }).collect(Collectors.toList());

        return newsIdList;
    }

}
